package com.zoe.wan.android.example.activity.search

import android.content.Intent
import android.os.Bundle
import android.text.Html
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.blankj.utilcode.util.KeyboardUtils
import com.zoe.wan.android.example.R
import com.zoe.wan.android.example.activity.webView.WebActivity
import com.zoe.wan.android.example.repository.data.SearchResultData

class SearchActivity : ComponentActivity() {

    companion object {
        const val INTENT_KEYWORD = "INTENT_KEYWORD"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            val keyword = intent.getStringExtra(INTENT_KEYWORD)
            val viewModel: SearchViewModel = viewModel()
            viewModel.input.set(keyword)
            viewModel.search()
            Column {
                SearchBar(viewModel)
                SearchResultList(viewModel)
            }

        }
    }

    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    fun SearchBar(viewModel: SearchViewModel) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .fillMaxWidth()
                .height(dimensionResource(id = R.dimen.dp_50))
                .background(colorResource(R.color.teal_700))
        ) {
            // 返回按钮
            IconButton(onClick = {
                finish()
            }) {
                Icon(
                    painter = painterResource(id = R.drawable.icon_back), contentDescription = "",
                    tint = Color.White,
                    modifier = Modifier.width(dimensionResource(id = R.dimen.dp_30))
                        .height(dimensionResource(id = R.dimen.dp_30))
                )
            }

            var inputValue = remember {
                mutableStateOf(viewModel.input.get())
            }
            //不想添加value使用以下这种方式
//            var inputValue by remember {
//                mutableStateOf(viewModel.input.get())
//            }

            // 输入框
            BasicTextField(
                value = inputValue.value ?: "", onValueChange = {
                    inputValue.value = it
                    viewModel.input.set(inputValue.value)
                },
                modifier = Modifier
                    .weight(1f)
                    .padding(
                        horizontal = dimensionResource(id = R.dimen.dp_10),
                        vertical = dimensionResource(id = R.dimen.dp_10)
                    )
                    .background(Color.White, shape = RoundedCornerShape(dimensionResource(id = R.dimen.dp_10)))
                    .height(dimensionResource(id = R.dimen.dp_40)),
                keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),
                keyboardActions = KeyboardActions(onSearch = {
                    // 点击搜索
                    viewModel.search()
                    // 隐藏键盘
                    KeyboardUtils.hideSoftInput(this@SearchActivity)
                }),
                decorationBox = { innerTextField ->
                    TextFieldDefaults.DecorationBox(
                        value = inputValue.value ?: "",
                        innerTextField = innerTextField,
                        enabled = true,
                        singleLine = true,
                        shape = RoundedCornerShape(dimensionResource(id = R.dimen.dp_15)),
                        visualTransformation = VisualTransformation.None,
                        interactionSource = remember { MutableInteractionSource() },
                        contentPadding = PaddingValues(start = dimensionResource(id = R.dimen.dp_10)),
                        colors = TextFieldDefaults.colors(
                            focusedIndicatorColor = Color.Transparent,
                            unfocusedIndicatorColor = Color.Transparent,
                            disabledIndicatorColor = Color.Transparent,
                            errorIndicatorColor = Color.Transparent,
                            focusedContainerColor = Color.White,
                            unfocusedContainerColor = Color.White,
                        )
                    )
                }
            )

            //清空按钮
            Text(text = "清空", color = Color.White, fontSize = 13.sp,
                modifier = Modifier.padding(end = dimensionResource(id = R.dimen.dp_10))
                    .clickable {
                        inputValue.value = ""
                        viewModel.input.set("")
                        viewModel.results.postValue(emptyList())
                        KeyboardUtils.hideSoftInput(this@SearchActivity)
                    })
        }
    }

    @Composable
    fun SearchResultList(viewModel: SearchViewModel) {
        val results = viewModel.results.observeAsState()
        LazyColumn {
            items(count = results.value?.size ?: 0) { index ->
                val item = results.value?.get(index)
                ListItem(item) {
                    // item点击时间
                    jumpToWeb(Html.fromHtml(item?.title).toString(), item?.link)
                }
            }
        }
    }

    @Composable
    fun ListItem(item: SearchResultData?, onClick: () -> Unit) {
        val annotatedText = buildAnnotatedString {
            val title = item?.title ?: ""
            var index = 0

            // 使用正则表达式查找 <em class='highlight'> 标签及其内容
            val regex = Regex("<em class='highlight'>(.*?)</em>")
            val matches = regex.findAll(title)

            // 逐步构建 AnnotatedString，添加不同样式的文本片段
            for (match in matches) {
                // 添加匹配前的普通文本
                append(title.substring(index, match.range.first))

                // 添加高亮文本
                withStyle(style = SpanStyle(color = Color.Red, fontWeight = FontWeight.Bold)) {
                    append(match.groupValues[1])
                }

                // 更新索引到下一个起始位置
                index = match.range.last + 1
            }

            // 添加剩余的普通文本
            if (index < title.length) {
                append(title.substring(index))
            }
        }

        // 使用自定义的 annotatedText 展示带样式的文本
        Text(
            text = annotatedText,
            modifier = Modifier
                .height(dimensionResource(id = R.dimen.dp_45))
                .padding(start = dimensionResource(id = R.dimen.dp_15))
                .clickable { onClick.invoke() }
                .wrapContentSize(align = Alignment.CenterStart),
            textAlign = TextAlign.Start
        )
    }

    private fun jumpToWeb(title: String?, url: String?) {
        val intent = Intent(this@SearchActivity, WebActivity::class.java)
        intent.putExtra(WebActivity.INTENT_WEB_TITLE_KEY, title)
        intent.putExtra(WebActivity.INTENT_WEB_URL_KEY, url)
        startActivity(intent)
    }
}